package jym.tan.movielibrary;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import org.eclipse.jdt.internal.jarinjarloader.RsrcURLStreamHandlerFactory;

public class Init {
	private static String[] params = new String[3]; 
	
	public static void main(String... args) throws MalformedURLException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException  {
		String jarPath = null;
		try {
			jarPath = new File(Init.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();
		} catch (Exception exception) {
		}
		params[0] = jarPath;
		ClassLoader classLoader = getClassloader();
		Thread.currentThread().setContextClassLoader(classLoader);
		
		Class<?> clazz = Class.forName("jym.tan.movielibrary.Launcher", true, classLoader);
		Method main = clazz.getMethod("main", new Class[] { args.getClass() });
		
		main.invoke((Object) null, new Object[] { params });		
	}

	private static ClassLoader getClassloader() throws MalformedURLException {
		ClassLoader parent = Init.class.getClassLoader();
		URL.setURLStreamHandlerFactory(new RsrcURLStreamHandlerFactory(parent));
		return new URLClassLoader(new URL[] {new URL("rsrc:client.jar"), new URL("rsrc:helper.jar"),
				new URL("rsrc:" + getSwtJarName()), 
				new URL("rsrc:miglayout-3.7.4.jar"),
				new URL("rsrc:spring-context-3.0.0.RELEASE.jar"),
				new URL("rsrc:spring-beans-3.0.0.RELEASE.jar"),
				new URL("rsrc:spring-core-3.0.0.RELEASE.jar"),
				new URL("rsrc:commons-logging-1.1.1.jar"),
				new URL("rsrc:spring-expression-3.0.0.RELEASE.jar"),
				new URL("rsrc:spring-asm-3.0.0.RELEASE.jar"),
				new URL("rsrc:log4j-1.2.14.jar"),
				new URL("rsrc:swingx-core-1.6.2-2.jar"),
				new URL("rsrc:DJNativeSwing.jar"),
				new URL("rsrc:DJNativeSwing-SWT.jar"),
				new URL("rsrc:commons-lang-2.6.jar"), 
				new URL("rsrc:gson-2.1.jar"),
				new URL("rsrc:imgscalr-lib-4.2.jar")}, parent);		
	}
	
	private static String getSwtJarName() {
		String osName = System.getProperty("os.name").toLowerCase();
		params[1] = osName;
		String swtFileNameOsPart = osName.contains("win") ? "win" : osName.contains("mac") ? "osx" : osName.contains("linux") || osName.contains("nix") ? "linux" : "";
		if ("".equals(swtFileNameOsPart)) {
			throw new RuntimeException("Launch failed: Unknown OS name: " + osName);
		}

		String swtFileNameArchPart = getArch();
		String swtFileName = "swt-" + swtFileNameOsPart + swtFileNameArchPart + "-3.7M5.jar";
		return swtFileName;
	}

	private static String getArch() {
		String jvmArch = System.getProperty("os.arch").toLowerCase();
		String arch = (jvmArch.contains("64") ? "64" : "32");
		params[2] = arch;
		return arch;
	}
}
